//
//  HZMallHomeViewController.m
//  app
//
//  Created by 刘华舟 on 15/5/11.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HZMallHomeViewController.h"
#import "HZMallSearchViewController.h"
#import "HZGoodsSalesViewController.h"
#import "HZMallGoodsListViewController.h"
#import "HZGoodsDetailViewController.h"
#import "SNWXVoiceTestViewController.h"

#import "HZHttpRequestURL.h"
#import "SNUniteUrl.h"

//view
#import "HZMallHomeSearchNaviBar.h"

//tool
#import "HZCachingURLCache.h"
#import "HZMallHttpManager.h"
#import "MyToast.h"
#import "JSONKit.h"
//categories
#import "UIWebView+AFNetworking.h"
//语音识别
#import "SNWXVoiceTestViewController.h"


//http://testtesttest.jiankangdr.com

@interface HZMallHomeViewController()<UIScrollViewDelegate, UIWebViewDelegate, HZMallHomeSearchNaviBarDelegate>

@property (strong, nonatomic) UIWebView *webView;
@property (strong, nonatomic) HZMallHomeSearchNaviBar *naviBackView;



@property (assign, nonatomic) BOOL fisrtLoadSuccess;

@end

@implementation HZMallHomeViewController

/*
 * Called when the view has completed loading. Time to set up our WebView!
 */
- (void) viewDidLoad {
    [super viewDidLoad];
    
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    
    self.webView = [[UIWebView alloc] initWithFrame:[self.view frame]];
    [self.webView setUserInteractionEnabled:YES];
    self.webView.delegate = self;
    self.webView.scrollView.delegate = self;
    self.webView.scrollView.contentInset = UIEdgeInsetsMake(0, 0, ktabBarHeight, 0);
    self.webView.scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, ktabBarHeight, 0);
    
    [self.view addSubview:self.webView];
    
    self.webView.scrollView.nothingRefreshView = [[UIRefreshNotingRefreshView alloc] initWithView:self.webView.scrollView viewController:self tryAgain:@selector(refreshData)];
    
    self.naviBackView = [[HZMallHomeSearchNaviBar alloc] initWithFrame:CGRectOf([self.ubo fx:UB_LEFT fy:UB_TOP], [self.ubo fw:UB_WIDTH oh:self.navigationAndStatusBarHeight])];
    self.naviBackView.delegate = self;
    [self.view addSubview:self.naviBackView];
    
    
    self.navigationController.navigationBar.hidden = YES;
    
    
    
    self.fisrtLoadSuccess = NO;
    
    [self.webView loadRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[SNUniteUrl shareUniteUrl].static_shoppageUrl]]];
    
    NSLog(@"首页：%@", [SNUniteUrl shareUniteUrl].static_shoppageUrl);
    NSLog(@"分类：%@", [SNUniteUrl shareUniteUrl].static_catogarypageUrl);
    
    [self.webView.scrollView.nothingRefreshView showLoadingMsg:nil errorMsg:@"加载失败，点击重试"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTabIndex:) name:kNotificationTabViewIndexChange object:nil];
    
    
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    self.navigationController.navigationBar.hidden = YES;
    
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    
    if (![[HZMallHttpManager shareHttpRequestMananger] networkReachable]) {
        [MyToast showDefaultBottonWithText:@"请检查网络设置"];
    }
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    if (!self.webView) {
        HZCachingURLCache *sharedCache = (HZCachingURLCache *)[NSURLCache sharedURLCache];
        [sharedCache removeAllCachedResponses];
    }
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark 切换主页的tabViewController.index
- (void)changeTabIndex:(NSNotification *)notice{
    NSDictionary *dict = notice.userInfo;
    NSString *index = [dict stringForKey:@"selectedIndex" nilValue:@"0"];
    
    if ([index integerValue] >= self.tabBarController.viewControllers.count || [index integerValue] < 0) {
        self.tabBarController.selectedIndex = 0;
    }else{
        self.tabBarController.selectedIndex = [index integerValue];
    }
}

#pragma mark 刷新页面
- (void)refreshData{
    
    if ([[HZMallHttpManager shareHttpRequestMananger] networkReachable]) {
        if (self.fisrtLoadSuccess) {
            //重新加载
            [self.webView reload];
        }else{
            [self.webView loadRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[SNUniteUrl shareUniteUrl].static_shoppageUrl]]];
        }
        
    }else{
        [self.webView loadRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[SNUniteUrl shareUniteUrl].static_shoppageUrl]]];
    }
}

#pragma mark UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    
    NSString *requestString = [[[request URL]  absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"requestString:%@",requestString);
    NSString *protocolString = @"http://localhost/";
    if ([requestString hasPrefix:protocolString]) {
        
        [webView stopLoading];
        
        requestString = [requestString substringFromIndex:protocolString.length];
        NSRange range = [requestString rangeOfString:@"?c="];
        NSString *path = [requestString substringToIndex:range.location];
        requestString = [requestString substringFromIndex:range.location+range.length];
        range = [requestString rangeOfString:@"&d="];
        
        NSString *callback = range.location == 0 ? @"":[requestString substringToIndex:range.location];
        
        NSString *jsonString = [requestString substringFromIndex:range.location+range.length];
        

        NSDictionary *jsonDict = [jsonString objectFromJSONString];
        

        //do something
        
        NSString *data = @"";
        
        
        //do something
        
        if ([path isEqualToString:kMallLocalPathTypeCategory]) {
            //跳到分类页面category:分类   {}
            
            self.tabBarController.selectedIndex = 1;
        }else if([path isEqualToString:kMallLocalPathTypeDetail]){
            //跳到商品详情页面detail:商品详情   {activities_id:10,shop_id:10,product_id:10}
            
            if ([jsonDict count]) {
                HZGoodsDetailViewController *detailVC = [[HZGoodsDetailViewController alloc] init];
                detailVC.shopID = [jsonDict stringForKey:APIKEY_mall_shop_id nilValue:@""];
                detailVC.productID = [jsonDict stringForKey:APIKEY_mall_product_id nilValue:@""];
                detailVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:detailVC animated:YES];
            }
            
        }else if([path isEqualToString:kMallLocalPathTypeList]){
            //跳到商品列表页面list:商品列表         {activities_id:100,name:''}
            if ([jsonDict count]) {
                
                HZMallGoodsListViewController *mallGoodsListVC = [[HZMallGoodsListViewController alloc] init];
                mallGoodsListVC.actID = [jsonDict stringForKey:@"activities_id" nilValue:@"-1"];
                if (![mallGoodsListVC.actID isEqualToString:@"-1"]) {
                    mallGoodsListVC.actName = [jsonDict stringForKey:APIKEY_mall_name nilValue:@"分类"];
                    mallGoodsListVC.hidesBottomBarWhenPushed = YES;
                    [self.navigationController pushViewController:mallGoodsListVC animated:YES];
                }
            }
            
        }else if([path isEqualToString:kMallLocalPathTypeWeb]){
            //跳到web页面 web:{url:'',name:''}
            if ([jsonDict count]) {
                HZGoodsSalesViewController *salesVC = [[HZGoodsSalesViewController alloc] init];
                salesVC.webTitle = [jsonDict stringForKey:APIKEY_mall_name nilValue:@""];
                salesVC.webURL = [jsonDict stringForKey:APIKEY_mall_url nilValue:@""];
                salesVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:salesVC animated:YES];
            }
            
        }else{
            
        }
        
        
        [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"kangxihui_callback('%@','%@',%@)", callback, path, data]];
    }

    
    return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
    

}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [self.webView.scrollView.nothingRefreshView remove];
    
    self.fisrtLoadSuccess = YES;
    

    
    [webView stringByEvaluatingJavaScriptFromString:@"kangxihui_debug=false"];

    [webView stringByEvaluatingJavaScriptFromString:@"$invoke=$iframe"];
    
}


- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    [self.webView.scrollView.nothingRefreshView activeStop];
    
    if (![[HZMallHttpManager shareHttpRequestMananger] networkReachable]) {
        [MyToast showDefaultBottonWithText:@"请检查网络设置"];
    }
}

#pragma mark HZMallHomeSearchNaviBarDelegate
//点击搜索
- (void)mallHomeSearchTap{
    HZMallSearchViewController *mallSrcVC = [[HZMallSearchViewController alloc] init];
    mallSrcVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:mallSrcVC animated:NO];

}

//点击语音搜索
- (void)mallHomeVoiceSearchTap{
//    [self refreshData];
    SNWXVoiceTestViewController * wxVoiceVC = [[SNWXVoiceTestViewController alloc] init];
    wxVoiceVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:wxVoiceVC animated:NO];
}

#pragma mark UIScrollViewDelegate 
//完成拖动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat offsetY = scrollView.contentOffset.y;
    if(0<scrollView.contentOffset.y <= [self.ubo fh:UB_1_3]){
       [self.naviBackView mallHomeBackGroundAlphaChange:offsetY/[self.ubo fh:UB_1_3]];
    }
}


@end
